<template>
  <div :class="check < 6 ? 'header' : 'header2'">
    <template v-if="check < 6">
      <div class="left"
           @click="router.push('/')">
        <img class="logoPic"
             src="../assets/img/nav/logo2.png"
             alt="" />
      </div>
      <div class="right">
        <div class="wallet"
             @click="reInit()">
          <p>
            {{
              address.slice(0, 5) +
              "..." +
              address.slice(address.length - 4, address.length)
            }}
          </p>
        </div>

        <div class="vip_div">
          <!-- <img
            src="../assets/img/nav/vip.png"
            @click="showSetPassword = true"
            alt=""
          /> -->
          <i style="font-weight: bold">T{{ level }}</i>
        </div>
        <img src="../assets/img/nav/lang.png"
             alt=""
             @click="langShow = !langShow" />

        <img src="../assets/img/nav/menu.png"
             alt=""
             @click="menuShow = !menuShow" />
      </div>
    </template>
    <template v-else>
      <div class="title">
        <div @click="clickRight">{{ rightTitle }}</div>
        <p>{{ title }}</p>
        <div class="img_d"
             @click="router.back()">
          <img src="../assets/img/nav/back2.png"
               alt="" />
        </div>
      </div>
    </template>
  </div>

  <!-- 菜单 -->
  <van-popup v-model:show="menuShow"
             position="left"
             :style="{ width: '100%', height: '100%' }">
    <div class="nav_pop">
      <div class="top">
        <img src="../assets/img/nav/logo2.png"
             alt="" />
        <img @click="menuShow = false"
             src="../assets/img/nav/back.png"
             alt="" />
      </div>
      <div class="section"
           @click="menu_s1 = !menu_s1">
        <p>{{ $t("hl_menu") }}</p>
        <img src="../assets/img/nav/down.png"
             alt="" />
      </div>
      <div class="url">
        <div class="box"
             v-for="x in nav_url"
             :key="x.check"
             @click="goRouter(x.url)">
          <div class="left">
            <img :src="x.img" />
            <div :class="{ urlCheck: check == x.check }">{{ x.title }}</div>
          </div>
          <img class="check"
               src="../assets/img/nav/check.png" />
        </div>
      </div>
      <div class="bottom">
        <div>
          <img src="../assets/img/nav/m1.png"
               alt="" />
          <p>facebook</p>
        </div>
        <div>
          <img src="../assets/img/nav/m2.png"
               alt="" />
          <p>telegram</p>
        </div>
      </div>
    </div>
  </van-popup>

  <!-- 语言 -->
  <van-popup v-model:show="langShow"
             position="left"
             :style="{ width: '100%', height: '100%' }">
    <div class="nav_pop">
      <div class="top">
        <img src="../assets/img/nav/logo.png"
             alt="" />
        <img @click="langShow = false"
             src="../assets/img/nav/back.png"
             alt="" />
      </div>
      <div class="section"
           @click="menu_s1 = !menu_s1">
        <p>{{ $t("hl_lang") }}</p>
        <img src="../assets/img/nav/down.png"
             alt="" />
      </div>

      <div class="url"
           v-if="menu_s2">
        <div class="box"
             @click="setLang('zh')">
          <div>简体</div>
          <img class="check"
               src="../assets/img/nav/check.png" />
        </div>
        <div class="box"
             @click="setLang('en')">
          <div>ENGLISH</div>
          <img class="check"
               src="../assets/img/nav/check.png" />
        </div>
        <div class="box"
             @click="setLang('hk')">
          <div>繁体</div>
          <img class="check"
               src="../assets/img/nav/check.png" />
        </div>
        <div class="box"
             @click="setLang('jp')">
          <div>日本語</div>
          <img class="check"
               src="../assets/img/nav/check.png" />
        </div>
        <div class="box"
             @click="setLang('kr')">
          <div>한국인</div>
          <img class="check"
               src="../assets/img/nav/check.png" />
        </div>
        <div class="box"
             @click="setLang('vn')">
          <div>Tiếng Việt</div>
          <img class="check"
               src="../assets/img/nav/check.png" />
        </div>
        <div class="box"
             @click="setLang('th')">
          <div>แบบไทย</div>
          <img class="check"
               src="../assets/img/nav/check.png" />
        </div>
      </div>
      <div class="bottom">
        <div>
          <img src="../assets/img/nav/m1.png"
               alt="" />
          <p>facebook</p>
        </div>
        <div>
          <img src="../assets/img/nav/m2.png"
               alt="" />
          <p>telegram</p>
        </div>
      </div>
    </div>
  </van-popup>

  <!-- 绑定 -->
  <template v-if="bindShow">
    <div class="bind_bg">
      <div class="bindView">
        <div class="pop_title"
             style="margin-bottom: 40px">
          {{ $t("hl_bindeUp") }}
        </div>

        <div class="pop_content">
          <h4 style="color: #333333">{{ $t("hl_inviteAddr") }}</h4>
          <textarea v-model="p_input"
                    name=""
                    id=""
                    cols="30"
                    rows="10"></textarea>
        </div>
        <!-- <div class="nav_pop_normal" @click="isNormal = !isNormal">
          <div :class="isNormal ? 'nav_pop_sel' : 'nav_pop_un'"></div>
          <p>{{ $t("hl_bindNormal") }}</p>
        </div> -->
        <div class="pop_btn">
          <p @click="goBind()">{{ $t("hl_bind") }}</p>
        </div>
      </div>
    </div>
  </template>
</template>

<script setup>
import { useRouter } from "vue-router";
import { ref, reactive, watch } from "vue";
import api from "../dapp/api";
// import { api_userInfo } from "../request/api";
import {
  showFailToast,
  showLoadingToast,
  showSuccessToast,
  closeToast,
} from "vant";
import i18n from "@/lang";
const emit = defineEmits(["getUserInfo", "clickRight"]);
const router = useRouter();
const Web3Modal = window.Web3Modal.default;
const WalletConnectProvider = window.WalletConnectProvider.default;
let web3Modal, network, provider, selectedAccount, gasPrice, web3;
let usdtContract, conContract;
const infura_key = "c3e254116c559ae5e58746e69fb38787";
let p_address = router.currentRoute.value.query.p_address;
let bindShow = ref(false);
let isNormal = ref(false);
let p_input = ref("");
let level = ref(0);
let address = ref("");
let menu_s1 = ref(true);
let menu_s2 = ref(true);
let menuShow = ref(false);
let langShow = ref(false);

let nav_url = reactive([
  {
    url: "/",
    check: 1,
    title: i18n.global.t("hl_tab1"),
    img: require("../assets/img/nav/n1.png"),
  },
  {
    url: "/trade",
    check: 2,
    title: i18n.global.t("hl_tab2"),
    img: require("../assets/img/nav/n2.png"),
  },
  {
    url: "/order",
    check: 3,
    title: i18n.global.t("hl_tab3"),
    img: require("../assets/img/nav/n3.png"),
  },
  {
    url: "/mine",
    check: 4,
    title: i18n.global.t("hl_tab4"),
    img: require("../assets/img/nav/n4.png"),
  },
  {
    url: "/ecology",
    check: 5,
    title: i18n.global.t("hl_tab5"),
    img: require("../assets/img/nav/n5.png"),
  },
  {
    url: "/whitepaper",
    check: 6,
    title: i18n.global.t("hl_tab6"),
    img: require("../assets/img/nav/n6.png"),
  },
]);

if (p_address && p_address.length == 42)
{
  p_input.value = p_address;
  console.log("p_input.value=", p_input.value, "p_address=", p_address);
}

const props = defineProps({
  check: {
    type: Number,
    default: 1,
  },
  title: {
    type: String,
    default: "",
  },
  rightTitle: {
    type: String,
    default: "",
  },
});

watch(isNormal, (newValue, oldValue) => {
  if (newValue)
  {
    p_input.value = "0x000000000000000000000000000000000000dEaD";
  } else
  {
    p_input.value = "";
  }
});

function clickRight () {
  emit("clickRight", {});
}

function reInit () {
  if (!conContract)
  {
    init();
  }
}

// console.log(11111);

// 登录钱包
async function init () {
  const providerOptions = {
    walletconnect: {
      package: WalletConnectProvider,
      options: {
        bridge: "https://uniswap.bridge.walletconnect.org",
        rpc: {
          56: "https://bsc-dataseed.binance.org/",
          66: "https://exchainrpc.okex.org",
          97: "https://data-seed-prebsc-0 - s3.binance.org:8545/",
          137: "https://polygon-rpc.com/",
        },
        infuraId: infura_key,
      },
    },
  };
  web3Modal = new Web3Modal({
    cacheProvider: false, // optional
    providerOptions, // required
    disableInjectedProvider: false, // optional. For MetaMask / Brave / Opera.
  });
  try
  {
    provider = await web3Modal.connect();
    provider.enable();
  } catch (e)
  {
    console.log("web3失败", e);
    return;
  }
  provider.on("accountsChanged", async (accounts) => {
    console.log("accounts :>> ", accounts);
    await fetchAccountData();
  });
  provider.on("chainChanged", async (chainId) => {
    console.log("chainId :>> ", chainId);
    await fetchAccountData();
  });
  provider.on("networkChanged", async (networkId) => {
    console.log("networkId :>> ", networkId);
    await fetchAccountData();
  });
  provider.on("disconnect", async (code, reason) => {
    console.log(code, reason);
    await onDisconnect();
  });
  await fetchAccountData(provider);
}
init();

// let signShow = false;
// 获取钱包地址
async function fetchAccountData () {
  // const web3 = new Web3(provider);
  // console.log("Web3.givenProvider", Web3.givenProvider);

  web3 = new Web3(Web3.givenProvider);
  const accounts = await web3.eth.getAccounts();
  selectedAccount = accounts[0];
  const provider3 = new ethers.providers.Web3Provider(window.ethereum);
  const network = await provider3.getNetwork();
  const chainId = network.chainId;

  if (chainId != 56)
  {
    Toast.fail(lang_list.topNav_warn1);
    onDisconnect();
  } else
  {
    address.value = selectedAccount;
    sessionStorage.setItem("address", address.value);
    console.log("chainId=", chainId, "| address=", address.value);

    // gasPrice = await web3.eth.getGasPrice();
    // gasPrice = Math.floor((await web3.eth.getGasPrice()) * 1.1); //110000000
    gasPrice = 110000000;
    // console.log("gasPrice-=-=-==", gasPrice);

    // 生成合约
    conContract = new web3.eth.Contract(conAbi, api.conAddress);
    // console.log("Contract=", conContract);




    checkUserInfo();
    return

    // let arrX = [];
    // setTimeout(() => {
    //   for (let index = 0; index < 140; index++)
    //   {
    //     conContract.methods
    //       .numToAddress(index)
    //       .call()
    //       .then(async (res) => {
    //         // console.log(index, "===", res);
    //         arrX.push(res);
    //       });
    //   }
    // }, 3000);


    // setTimeout(() => {
    //   console.log(arrX);

    // }, 5000);


    let addressArr = [];
    let levelArr = [];
    let redirectsArr = [];
    let leaderArr = [];
    let isEfficientArr = [];
    let outAmountArr = [];
    let getAmountArr = [];
    let investAmountArr = [];
    let partnerArr = [];
    let systemPartnerArr = [];
    let nodeArr = [];
    let NewnumArr = [];
    let stateArr = [];
    let availableActivationArr = [];
    let pppArr = [];
    let freezeArr = [];

    for (let index = 0; index < 40; index++)
    {
      const element = api.array140[index];
      await conContract.methods
        .getUserInfo(element)
        .call()
        .then(async (res) => {
          // addressArr.push(element);
          // levelArr.push(res.level);
          // redirectsArr.push(res.redirects);
          // leaderArr.push(res.leader);
          // isEfficientArr.push(res.isEfficient);
          // outAmountArr.push(res.outAmount);
          // getAmountArr.push(res.getAmount);
          // investAmountArr.push(res.investAmount);
          // partnerArr.push(Boolean(res.partner));
          // systemPartnerArr.push(res.systemPartner);
          // availableActivationArr.push(res.availableActivation);
          // nodeArr.push(res.node);
          // NewnumArr.push(res.Newnum);
          // stateArr.push(res.state);
          pppArr.push(res.PPP);

        });

      // await conContract.methods
      //   .getfreeze(element)
      //   .call()
      //   .then(async (res) => {
      //     addressArr.push(element);
      //     freezeArr.push(res);
      //   });
    }

    setTimeout(() => {
      // console.log(addressArr);
      // console.log(levelArr);
      // console.log(redirectsArr);
      // console.log(leaderArr);
      // console.log(isEfficientArr);
      // console.log(outAmountArr);
      // console.log(getAmountArr);
      // console.log(investAmountArr);
      // console.log(partnerArr);
      // console.log(systemPartnerArr);
      // console.log(availableActivationArr);
      // console.log(nodeArr);
      // console.log(NewnumArr);
      // console.log(stateArr);
      console.log(pppArr);
      // console.log(freezeArr);
    }, 5000);





  }
}

function checkUserInfo () {

  try
  {
    // 查询用户信息;
    conContract.methods
      .getUserInfo(address.value)
      .call()
      .then(async (res) => {
        console.log("getUserInfo=", res);
        level.value = Number(res.level);
        if (res.leader == "0x0000000000000000000000000000000000000000")
        {
          bindShow.value = true;
        } else
        {
          emit("getUserInfo", {
            address: address.value,
            userData: res,
            web3: web3,
            gasPrice: gasPrice,
          });
        }
      });
  } catch (e)
  {
    console.error(e);
  }
}

// 断开链接
async function onDisconnect () {
  if (address.value)
  {
    await web3Modal.clearCachedProvider();
    await provider.disconnect();
    provider = null;
    selectedAccount = null;
    address.value = "";
  }
}

async function goBind () {
  showLoadingToast({
    message: i18n.global.t("gg_loading"),
    forbidClick: true,
    duration: 3000,
  });

  if (
    p_input.value == "" ||
    p_input.value == null ||
    p_input.value.length != 42
  )
  {
    showFailToast(i18n.global.t("hl_inputInvite"));
    return;
  }

  try
  {
    conContract.methods
      .invite(p_input.value)
      .send({
        from: address.value,
        gas: 100000,
        gasPrice: gasPrice,
      })
      .on("transactionHash", (hash) => {
        showLoadingToast({
          message: i18n.global.t("hl_waitLink"),
          forbidClick: true,
          duration: 0,
        });
      })
      .on("receipt", (receipt) => {
        closeToast();
        showSuccessToast(i18n.global.t("hl_opSucc"));
        bindShow.value = false;
        setTimeout(() => {
          checkUserInfo();
        }, 2500);
      })
      .on("error", (error, receipt) => {
        closeToast();
        showFailToast(i18n.global.t("hl_opFail"));
      });
  } catch (e)
  {
    console.log("e :>> ", e);
  }

  // api_bindUser({
  //   address: address.value,
  //   p_address: p_input.value,
  // }).then((res) => {
  //   // closeToast();
  //   if (res.code == 200) {
  //     showSuccessToast(i18n.global.t("hl_opSucc"));
  //     setTimeout(() => {
  //       location.reload();
  //     }, 2500);
  //   } else {
  //     // showFailToast(i18n.global.t("hl_opFail"));
  //     isNormal.value = false;
  //   }
  // });
}

function getUrlParam (name) {
  var reg = new RegExp("(^|&)" + name + "=([^&]*)(&|$)"); //构造一个含有目标参数的正则表达式对象
  var r = window.location.search.substr(1).match(reg); //匹配目标参数
  if (r != null) return unescape(r[2]);
  return null; //返回参数值
}

function setLang (lang) {
  localStorage.setItem("lang", lang);
  location.reload();
}

function goRouter (url) {
  // if (url == "https://chatforai.com/") {
  //   window.location.href = "https://chatforai.com/";
  //   return;
  // }
  router.push(url);
  menuShow.value = false;
}
</script>

<style scoped lang="less">
.header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px;
  border-bottom: #f7f7ff solid 1px;
  height: 52px;
  background: #1296db;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  z-index: 1000;

  .left {
    display: flex;
    align-items: center;

    .logoPic {
      height: 40px;
    }

    .logoText {
      width: 60px;
      margin-left: 10px;
    }
  }

  .right {
    display: flex;
    align-items: center;

    .level {
      // background: url("../assets/img/icon_vip.png") no-repeat;/
      background-size: 100% 100%;
      height: 32px;
      width: 32px;
      line-height: 32px;
      color: white;
      text-align: center;
      margin-right: 6px;
    }

    p {
      border-radius: 4px;
      color: white;
    }

    .wallet {
      display: flex;
      align-items: center;
      // background: linear-gradient(to bottom, #1296db, #0caa09);
      background: #dbbb97;
      padding: 6px 10px;
      border-radius: 8px;
      margin-right: 8px;

      p {
        color: #1296db;
      }

      img {
        height: 20px;
        margin-right: 4px;
      }
    }

    .vip_div {
      display: flex;
      align-items: center;
      padding: 6px 10px;
      border-radius: 8px;

      i {
        color: #dbbb97;
        font-size: 17px;
        margin-left: -2px;
      }

      img {
        height: 20px;
        margin-right: 4px;
      }
    }

    img {
      height: 32px;
      margin-right: 8px;
    }
  }

  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;

    .img_d {
      // width: 30px;
      display: flex;
      align-items: center;

      img {
        width: 36px;
        padding: 4px;
      }
    }

    p {
      height: 100%;
      line-height: 100%;
      margin: 0 auto;
      text-align: center;
      font-size: 18px;
      color: black;
    }

    div {
      min-width: 40px;
      padding: 10px 4px;
      font-size: 14px;
      color: #0caa09;
      text-align: right;
    }
  }
}

.header2 {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 4px;
  border-bottom: #f7f7ff solid 1px;
  height: 52px;
  background: white;
  position: fixed;
  left: 0;
  top: 0;
  width: 100%;
  z-index: 1000;

  .title {
    display: flex;
    align-items: center;
    justify-content: space-between;
    width: 100%;

    .img_d {
      display: flex;
      align-items: center;

      img {
        height: 36px;
        padding: 4px;
      }
    }

    p {
      height: 100%;
      line-height: 100%;
      margin: 0 auto;
      text-align: center;
      font-size: 18px;
      color: black;
    }

    div {
      min-width: 40px;
      padding: 10px 4px;
      font-size: 14px;
      color: #0caa09;
      text-align: right;
    }
  }
}

.nav_pop {
  height: 100%;
  background: rgba(0, 0, 0, 0.8);
  padding: 3%;
  .top {
    display: flex;
    align-items: center;
    justify-content: space-between;

    img {
      height: 40px;
      padding: 4px;
    }
  }

  .section {
    display: flex;
    align-items: center;
    justify-content: space-between;
    background: #dbbb97;
    margin: 12px 0;
    height: 52px;
    line-height: 52px;
    padding: 0 20px;
    border-radius: 8px;

    p {
      color: #1296db;
      font-size: 19px;
    }

    img {
      height: 32px;
    }
  }

  .url {
    .box {
      margin-bottom: 15px;
      position: relative;
      border-bottom: 1px solid #999;
      color: #dbbb97;
      div {
        padding-left: 10px;
        font-size: 18px;
        line-height: 40px;
      }

      .urlCheck {
        color: #dbbb97;
      }

      .line {
        width: 100%;
      }

      .left {
        display: flex;
        align-items: center;
        color: #dbbb97;
        img {
          height: 24px;
          margin-right: 6px;
        }
      }

      .check {
        position: absolute;
        right: 8px;
        top: 50%;
        transform: translateY(-50%);
        width: 15px;
      }
    }
  }

  .bottom {
    padding-top: 40px;

    display: flex;
    align-items: center;

    div {
      width: 100px;
      height: 100px;
      img {
        height: 40px;
        margin: 6px auto;
      }

      p {
        color: #dbbb97;
        width: 100%;
        text-align: center;
      }
    }
  }
}

.van-popup {
  // background: rgba(0, 0, 0, 0.85);
}

:deep(.van-password-input__item) {
  border: 2px solid rgba(0, 194, 152, 0.25);
  border-radius: 5px;
}

.bind_bg {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background: linear-gradient(to bottom, #ffffff, #d6fff6);
  backdrop-filter: blur(2px);
  z-index: 1001;
  display: flex;
  align-items: center;

  .bindView {
    padding-bottom: 75%;
    margin: 0 auto;
    width: 100%;
    border-radius: 10px;

    .pop_title {
      width: 60%;
      margin: 10% auto;
      font-size: 24px;
      white-space: pre-wrap;
      word-break: break-all;
      word-wrap: break-word;
      color: #333333;
      text-align: center;
    }

    .bindBackView {
      width: 60%;
      margin: 0 auto;
      margin-top: -35%;
    }

    .pop_content {
      width: 90%;
      margin: 5%;

      textarea {
        width: 100%;
        height: 60px;
        border-radius: 4px;
        font-size: 16px;
        padding: 6px;
        box-shadow: 0.5px 0.5px #1296db;
        color: black;
      }

      h4 {
        text-align: left;
        margin-bottom: 12px;
      }
    }

    .nav_pop_normal {
      display: flex;
      align-items: center;
      justify-content: center;
      margin: 10px 0;

      div {
        display: flex;
        align-items: center;
        justify-content: center;
        height: 20px;
        width: 20px;
        border-radius: 4px;
        padding: 2px;
        margin-right: 12px;
      }

      .nav_pop_sel {
        background: #1296db;
        border: 1px #1296db solid;
      }

      .nav_pop_un {
        border: 1px #1296db solid;
        background: white;
      }
    }
  }

  .pop_btn {
    display: flex;
    align-items: center;
    justify-content: space-evenly;

    p {
      width: 90%;
      text-align: center;
      border-radius: 10px;
      height: 44px;
      margin: 20px 0;
      padding: 0 24px;
      line-height: 44px;
      color: white;
      background: #1296db;
      font-size: 16px;
    }
  }
}

.pop {
  background: white;
  padding: 5%;
  border-top-right-radius: 30px;
  border-top-left-radius: 30px;

  .tit {
    display: flex;
    align-items: center;
    justify-content: space-between;
    border-bottom: 1px solid #efefef;
    margin-bottom: 12px;
    padding-bottom: 12px;
    p {
      font-size: 20px;
      color: #606060;
    }

    img {
      height: 28px;
    }
  }

  .name {
    display: flex;
    align-items: center;
    justify-content: space-between;

    p {
      font-size: 15px;
      color: #606060;
    }
    h5 {
      font-size: 13px;
      color: #606060;
    }
  }

  input {
    border: 2px solid rgba(0, 194, 152, 0.25);
    height: 40px;
    margin: 12px 0;
    border-radius: 8px;
    width: 100%;
    box-shadow: 0.5px 0.5px #1296db;
  }

  textarea {
    border: 2px solid rgba(0, 194, 152, 0.25);
    height: 60px;
    margin: 12px 0;
    border-radius: 8px;
    width: 100%;
    padding: 2%;
    box-shadow: 0.5px 0.5px #1296db;
  }

  .btn {
    width: 100%;
    height: 40px;
    line-height: 40px;
    color: white;
    background: #1296db;
    text-align: center;
    border-radius: 8px;
    margin: 20px 0;
  }

  h4 {
    font-size: 11px;
    color: #606060;
    font-weight: 400;
  }
}

.pwd_bg {
  width: 100vw;
  height: 100vh;
  position: fixed;
  top: 0;
  left: 0;
  background: linear-gradient(to bottom, #ffffff, #d6fff6);
  backdrop-filter: blur(2px);
  z-index: 1001;
  display: flex;
  align-items: center;

  .bindView {
    padding-bottom: 75%;
    margin: 0 auto;
    width: 100%;
    border-radius: 10px;

    .pop_title {
      width: 60%;
      margin: 10% auto;
      font-size: 24px;
      white-space: pre-wrap;
      word-break: break-all;
      word-wrap: break-word;
      color: #333333;
      text-align: center;
    }

    .pop_content {
      width: 90%;
      margin: 5%;

      h4 {
        text-align: left;
        margin-bottom: 12px;
      }
    }
  }

  .btn {
    width: 90%;
    text-align: center;
    border-radius: 10px;
    height: 44px;
    margin: 20px auto;
    padding: 0 24px;
    line-height: 44px;
    color: white;
    background: #1296db;
    font-size: 16px;
  }
}
</style>
